# -*- coding: utf-8 -*-
# @Date   : 2020/1/19
# @File   : AC04_ConsLoanAmt_Change_Ratio.py
# @Author : zhaochen

'''eof
name:个人消费贷款金额_change_ratio
code:AC04_ConsLoanAmt_Change_Ratio
tableName:
columnName:
groups:AC模块
dependencies:EG_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''


import sys
import json
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def isFloat(x):
    '''
    判断x为float类型且大于等于0
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def getRatingInfoData(code, interface=None, last=False):
    '''
    获取上次评级信息的指标值或接口数据，默认返回的格式是tuple(val, "value") 指标值和标记
    标记分为 'value':指标值 'data':数据
    :param code: 要获取的指标值的指标code
    :param interface: EC_DSJ_2D/IC_DSJ_2D/TX_CQ_DSJ
    :return:
    '''
    try:
        historyRatingInfo = json.loads(ratingRequest.get("historyRatingInfo"))
        if last:
            # 获取上次评级数据信息
            ratingInfo = historyRatingInfo.get("lastRatingInfo")
        else:
            # 获取本次评级数据
            ratingInfo = historyRatingInfo.get("ratingInfo")
        # 如果是取score 或者 ratingLevel 直接返回
        if code in ["score", "ratingLevel"]:
            score = ratingInfo.get(code)
            try:
                return float(score), "value"
            except:
                return None, None
        # 取数据类型进行判断
        dataType = ratingInfo.get("dataType")
        # 如果传回来是数据 则返回相应接口里面的数据data
        if dataType == "1":
            data = ratingInfo.get(interface).get("data")
            if isinstance(data, dict):
                return (data, "data")
            else:
                return None, None
        # 如果传回来是指标值，则通过code进行提取
        elif dataType == "2":
            val = ratingInfo.get(code)
            if val in null_type_list:
                return None, None
            else:
                try:
                    return float(val), "value"
                except:
                    return None, None
        else:
            return None, None
    except:
        return None, None

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)

    if occurTimes == 1:
        if table == "":
            return ""
        if table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)

def dateFormat(time):
    try:
        import re
        import datetime
        r1 = re.compile(u'年|月|日')
        time = r1.sub('.', time)
        try:
            date = datetime.datetime.strptime(time, '%Y.%m.%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y-%m-%d')
            except:
                try:
                    date = datetime.datetime.strptime(time, '%Y/%m/%d')
                except:
                    try:
                        r = re.compile(r'\D+')
                        tmp = r.sub('', time)
                        if len(tmp) > 8:
                            tmp = tmp[:8]
                        date = datetime.datetime.strptime(tmp, '%Y%m%d')
                    except:
                        date = None
        return date
    except:
        return None

def consLoanAmt2D(data):
    factor = []
    # 借贷账户信息 PDA[1.1]
    PDA = getTable(data, 'PDA', 1)
    if PDA is None:
        return None
    elif PDA == [{}] or PDA == "":
        return 0
    else:
        # 借贷账户信息单元 PD01[0.*]
        PD01 = getTable(PDA[0], 'PD01', 0)
        if PD01 is None or PD01 == "":
            return None
        elif PD01 == [{}]:
            return 0
        else:
            for i in PD01:
                try:
                    # 基本信息段 PD01A[1.1]
                    PD01A = getTable(i, 'PD01A', 1)
                    if PD01A is None or PD01A == "":
                        factor.append(None)
                    elif PD01A == [{}]:
                        factor.append(0)
                    else:
                        # 业务种类
                        PD01AD03 = PD01A[0].get("PD01AD03")
                        # 借款金额
                        PD01AJ01 = PD01A[0].get("PD01AJ01")
                        # # 账户授信额度
                        # PD01AJ02 = PD01A[0].get("PD01AJ02")

                        if PD01AD03 not in null_type_list:
                            if PD01AD03 == "91":
                                if isFloat(PD01AJ01):
                                    factor.append(float(PD01AJ01))
                                else:
                                    factor.append(None)
                            else:
                                factor.append(0)
                        else:
                            factor.append(None)
                except:
                    factor.append(None)
                    continue

    factor = [x for x in factor if x is not None]
    factor = filter(lambda x:x is not None, factor)
    if len(factor) == 0:
        return None
    else:
        return sum(factor)

def getTable1d(data, table_Name):
    try:

        data = data.get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}] #ReportNo EC是大写 IC 是reportNo 小写
            if isinstance(data, list) and len(data) == 1 and data[0]['reportNo'] in null_type_list:
                return [{}]
            # 存在表 但为空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None

def consLoanAmt1D(data):
    try:
        ICRLoanInfo002Loan = getTable1d(data, 'ICRLoanInfo002*Loan')
        if ICRLoanInfo002Loan is None:
            return None
        elif ICRLoanInfo002Loan == [{}]:
            return 0
        else:
            flag = []
            result = []
            for i in ICRLoanInfo002Loan:
                loanType = i.get('loanType')
                amount = i.get("creditLimitAmount")
                if loanType in null_type_list or amount in null_type_list:
                    flag.append(None)
                    continue
                else:
                    if i.get('loanType') == u'个人消费贷款':
                        if isFloat(amount):
                            result.append(float(amount))
                        else:
                            flag.append(None)
                    else:
                        result.append(0)
            if len(flag) == len(ICRLoanInfo002Loan):
                return None
            else:
                return sum(result)
    except:
        return None

# 当前申请数据
def factor1():
    data, data_type = getRatingInfoData('consLoanAmt2D', interface='IC_DSJ_2D', last=False)
    if data_type == 'value':
        try:
            return float(data)
        except:
            return None
    elif data_type == 'data':
        res = consLoanAmt2D(data)
        return res
    else:
        return None

def factor2():
    data, data_type = getRatingInfoData('consLoanAmt1D', interface='IC_DSJ', last=True)
    if data is None:
        # 如果一代的数据没有，则使用二代的数据去取
        data, data_type = getRatingInfoData('consLoanAmt2D', interface='IC_DSJ_2D', last=True)
        if data_type == 'value':
            try:
                return float(data)
            except:
                return None
        elif data_type == 'data':
            res = consLoanAmt2D(data)
            return res
        else:
            return None
    else:
        if data_type == 'value':
            try:
                return float(data)
            except:
                return None
        elif data_type == 'data':
            res = consLoanAmt1D(data)
            return res
        else:
            return None


def AC04_ConsLoanAmt_Change_Ratio():
    f1 = factor1()
    f2 = factor2()

    try:
        res = (float(f1) - float(f2)) / float(f2)
        return round(res,4)
    except:
        return u'缺失值'

result = AC04_ConsLoanAmt_Change_Ratio()

